<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-28
 * Time: 14:32
 * 商品详情 点击加入购物车 或者 直接结算
 */

namespace app\api\service\product;


use app\api\model\Goods;
use app\api\model\GoodsOrderContent;
use app\api\model\User;
use app\api\service\Token;
use app\lib\exception\ParameterException;

class CreateOrderContentSer extends Token
{
    /**
     * 1.判断数据，有修改，没有的话，添加
     */
    // 用户信息
    private $user;

    // 商品信息
    private $goods;

    // 传的数据
    private $postArr;

    // 购物车信息
    private $goodsOrderContent;

    function __construct($postArr)
    {
        $this->postArr = $postArr;
        $this->user = User::get(self::getCurrentUid());
        $this->goods = Goods::where('id',$this->postArr['goods_id'])->with('image')->find();
        $this->goodsOrderContent = GoodsOrderContent::where('order_id',0)
            ->where('goods_id',$this->postArr['goods_id'])
            ->where('user_id',$this->user['id'])
            ->find();
    }

    // 入口方法
    public function entrance()
    {
        return $this->judgeData();
    }

    // 判断数据
    private function judgeData()
    {
        if(!$this->goods) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '商品不存在'
                ]
            ]);
        }
        if($this->goods['up_down'] == 2) {
            throw new ParameterException([
                'msg' => [
                    'goods' => '商品已下架'
                ]
            ]);
        }
        return $this->createUpdateData();
    }

    // 创建或更新数据
    private function createUpdateData()
    {
        if($this->goodsOrderContent) {
            if($this->postArr['status'] == 1) {
                $number = $this->goodsOrderContent['number'] + $this->postArr['number'];
            } else {
                $number = $this->postArr['number'];
            }
            if($number > $this->goods['number']) {
                throw new ParameterException([
                    'msg' => [
                        'goods' => '库存不足'
                    ]
                ]);
            }
            GoodsOrderContent::where('id',$this->goodsOrderContent['id'])->update([
                'number' => $number
            ]);
        } else {
            $number = $this->postArr['number'];
            if($number > $this->goods['number']) {
                throw new ParameterException([
                    'msg' => [
                        'goods' => '库存不足'
                    ]
                ]);
            }
            GoodsOrderContent::create([
                'number' => $number,
                'price' => $this->goods['price'],
                'goods_id' => $this->goods['id'],
                'goods_sort_id' => $this->goods['sort_id'],
                'user_id' => $this->user['id'],
                'goods_name' => $this->goods['name'],
                'img_id' => $this->goods['image']['img_id'],
            ]);
        }
        return writeJson(201, [], '操作成功！');
    }
}